package com.sskj.aikeeper;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hjq.toast.ToastUtils;
import com.sskj.aikeeper.bean.CetificationBean;
import com.sskj.aikeeper.bean.Menu;
import com.sskj.aikeeper.bean.NoticeListBean;
import com.sskj.aikeeper.component.DaggerUserDataComponent;
import com.sskj.aikeeper.hangqing.activity.CertificationActivity;
import com.sskj.aikeeper.hangqing.activity.NoticeActivity;
import com.sskj.aikeeper.hangqing.activity.SafeCenterActivity;
import com.sskj.aikeeper.hangqing.activity.SettingActivity;
import com.sskj.aikeeper.hangqing.activity.ShareActivity;
import com.sskj.aikeeper.hangqing.activity.UserInfoActivity;
import com.sskj.aikeeper.hangqing.activity.NicknameActivity;
import com.sskj.aikeeper.http.MarketWebSocket;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.GSonUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.HideUtil;
import com.sskj.lib.widget.TipDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainPresenter> {
    @BindView(R.id.main_content)
    FrameLayout mainContent;
    @BindView(R.id.tab_layout)
    CommonTabLayout tabLayout;
    @BindView(R.id.main_drawer_layout)
    DrawerLayout mDrawerLayout;

    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    ArrayList<Fragment> fragments = new ArrayList<>();
    HashMap<Integer, Fragment> tabMap = new HashMap<>();
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.tv_withdraw)
    TextView tvWithdraw;
    @BindView(R.id.tv_transfer)
    TextView tvTransfer;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btn_logout)
    Button btnLogout;
    @BindView(R.id.view)
    View view;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private int curPos = 0;

    private int chooseTab;

    List<Menu> menuData = new ArrayList<>();
    private BaseAdapter<Menu> adapter;
    MarketWebSocket marketWebSocket;

    private int cetification = 1;
    private NotificationManager mNotificationManager;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter getPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void dealFirstSaveInstance(Bundle savedInstanceState) {
        FragmentManager mManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            List<Fragment> fragments = mManager.getFragments();
            FragmentTransaction fragmentTransaction = mManager.beginTransaction();
            for (int i = 0; i < fragments.size(); i++) {
                fragmentTransaction.remove(fragments.get(i));
            }
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*身份认证状态*/
        if (SPUtil.get(SPConfig.LOGIN, false)) {
            mPresenter.getCertificationStatus();
        }
        startBBWebSocket();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (SPUtil.get(SPConfig.LOGIN, false)) {
            mPresenter.getCertificationStatus();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeMarket();
    }

    private void startBBWebSocket() {
        closeMarket();
        JSONObject message = new JSONObject();
        try {
            message.put("sub", "ticker@all");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        marketWebSocket = new MarketWebSocket(BaseHttpConfig.WS_BB_MARKET, "bb", message.toString());
        marketWebSocket.setLogEnable(true);
        marketWebSocket.setListener(message1 -> {
            CoinBean coinBean = GSonUtil.GsonToBean(message1, CoinBean.class);
            if (coinBean != null) {
                coinBean.setSocket(true);
                RxBus.getDefault().post(coinBean);
            }
        });

    }

    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.app_mainActivity1), R.mipmap.icon_shouye_no, R.mipmap.icon_shouye_yes));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.app_hangqingFragment1), R.mipmap.icon_hangqing_no, R.mipmap.icon_hangqing_yes));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.app_mainActivity3), R.mipmap.icon_shequ_no, R.mipmap.icon_shequ_yes));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.app_mainActivity4), R.mipmap.icon_yingyong_no, R.mipmap.icon_yingyong_yes));
        tabEntities.add(new TabItem(App.INSTANCE.getString(R.string.app_mainActivity5), R.mipmap.icon_qianbao_no, R.mipmap.icon_qianbao_yes));
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HOME).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_HANGQING).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.COMMUNITY_FRAGMENT_COMMUNITY).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.FUNCTIONS_FRAGMENT_FUNCTIONS).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.WALLET_FRAGMENT).navigation());
        tabLayout.setTabData(tabEntities);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 4) {
                    if (!checkLogin()) {
                        tabLayout.setCurrentTab(chooseTab);
                        return;
                    }
                }
                chooseTab = position;
                changeTab(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.main_content, fragments.get(0))
                .add(R.id.main_content, fragments.get(1))
                .hide(fragments.get(1))
                .show(fragments.get(0))
                .commitAllowingStateLoss();
        tabMap.put(0, fragments.get(0));
        tabMap.put(1, fragments.get(1));
        initDrawerLayout();
        initDrawerRecycler();
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        /*身份认证状态*/
        if (SPUtil.get(SPConfig.LOGIN, false)) {
            mPresenter.getCertificationStatus();
            mPresenter.getNotification(System.currentTimeMillis() / 1000, 1, 1);
        }
        userViewModel.getUsers().observe(this, new Observer<List<UserData>>() {
            @Override
            public void onChanged(@Nullable List<UserData> users) {
                if (users != null && users.size() > 0) {
                    userData = users.get(0);
                    tvName.setText("Hi," + userData.getNickname());
                    tvMobile.setText(HideUtil.getPhoneHide(userData.getMobile()));
                    btnLogout.setVisibility(View.VISIBLE);
                } else {
                    userData = null;
                    tvName.setText(App.INSTANCE.getString(R.string.app_mainActivity6));
                    tvMobile.setText(App.INSTANCE.getString(R.string.app_mainActivity7));
                    btnLogout.setVisibility(View.GONE);
                }
            }
        });
        //充币
        ClickUtil.click(300, tvRecharge, () -> {
            if (checkCetification()) {
                ARouter.getInstance().build(RConfig.WALLET_ACTIVITY_RECHARGE).navigation();
            }
            closeDrawerLayout();
        });
        //提币
        ClickUtil.click(300, tvWithdraw, () -> {
            if (checkCetification()) {
                ARouter.getInstance().build(RConfig.WALLET_ACTIVITY_WITHDRAW).navigation();
            }
            closeDrawerLayout();
        });
        //站内转账
        ClickUtil.click(300, tvTransfer, () -> {
            if (checkCetification()) {
                ARouter.getInstance().build(RConfig.WALLET_ACTIVITY_TRANSFER_STATE).navigation();
            }
            closeDrawerLayout();
        });
        //去登录
        ClickUtil.click(300, view, () -> {
            if (userData == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN_NUMBER).navigation();
                overridePendingTransition(com.sskj.lib.R.anim.lib_anim_in, com.sskj.lib.R.anim.lib_anim_out);
                closeDrawerLayout();
            }
        });
        //退出登录
        ClickUtil.click(300, btnLogout, () -> {
            LogoutProvider logoutProvider = new LogoutProviderImpl();
            logoutProvider.logout();
        });
    }

    private boolean checkLogin() {
        if (userData == null) {
            ARouter.getInstance().build(RConfig.APP_LOGIN_NUMBER).navigation();
            overridePendingTransition(com.sskj.lib.R.anim.lib_anim_in, com.sskj.lib.R.anim.lib_anim_out);
//            new TipDialog(this)
//                    .setTitleText(App.INSTANCE.getString(R.string.app_homeFragment2))
//                    .setContentText(App.INSTANCE.getString(R.string.app_homeFragment3))
//                    .setListener(dialog -> ARouter.getInstance().build(RConfig.APP_LOGIN_NUMBER).navigation())
//                    .show();
            return false;
        }
        return true;
    }

    private void changeTab(int position) {
        if (tabMap.get(position) == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_content, fragments.get(position))
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
            tabMap.put(position, fragments.get(position));
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
        }
        curPos = position;
    }

    private void initDrawerRecycler() {
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_userInfoActivity1), R.mipmap.icon_geren, UserInfoActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_certificationActivity1), R.mipmap.icon_sfrz, CertificationActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_safeCenterActivity1), R.mipmap.icon_anquan, SafeCenterActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_noticeActivity1), R.mipmap.icon_xiaoxi, NoticeActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_shareActivity1), R.mipmap.icon_fenxiang03, ShareActivity.class));
        menuData.add(new Menu(App.INSTANCE.getString(R.string.app_settingActivity1), R.mipmap.icon_shezhi, SettingActivity.class));
        HashMap<Integer, String> status = new HashMap<>();
        status.put(1, App.INSTANCE.getString(R.string.app_mainActivity16));
        status.put(2, App.INSTANCE.getString(R.string.app_mainActivity17));
        status.put(3, App.INSTANCE.getString(R.string.app_mainActivity18));
        status.put(4, App.INSTANCE.getString(R.string.app_mainActivity19));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<Menu>(R.layout.app_item_drawer, null, recyclerView, false) {
            @Override
            public void bind(ViewHolder holder, Menu item) {
                holder.setImageResource(R.id.iv_drawer, item.getIcon())
                        .setText(R.id.tv_drawer, item.getText())
                        .setText(R.id.tv_certification, status.get(cetification))
                        .setVisible(R.id.tv_certification, userData != null && holder.getAdapterPosition() == 1);
            }
        };
        adapter.setNewData(menuData);
        ItemClickSupport.addTo(recyclerView).setOnItemClickListener((recyclerView, position, v) -> {
            if (position == 5) {
                startActivity(new Intent(this, menuData.get(position).getClz()));
                return;
            }
            if (!checkLogin()) {
                return;
            }
            if (position != 1) {
                startActivity(new Intent(this, menuData.get(position).getClz()));
            } else {
                switch (cetification) {
                    case 1:
                        startActivity(new Intent(this, menuData.get(position).getClz()));
                        break;
                    default:
                        ARouter.getInstance().build(RConfig.APP_ACTIVITY_CERTIFICATION_RESULT)
                                .withInt(Constans.CERTIFICATION_STATUS, cetification)
                                .navigation();
                        break;
                }
            }
            closeDrawerLayout();
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.DRAWER_OPEN)
    public void openDrawer() {
        if (SPUtil.get(SPConfig.LOGIN, false)) {
            mPresenter.getCertificationStatus();
        }
        openDrawerLayout();
    }

    public void openDrawerLayout() {
        mDrawerLayout.openDrawer(Gravity.LEFT);
    }

    public void closeDrawerLayout() {
        mDrawerLayout.closeDrawers();
    }

    private void initDrawerLayout() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//禁止滑动开启
    }

    public void getStatusOK(CetificationBean data) {
        if (data == null) {
            return;
        }
        SPUtil.put(SPConfig.CETIFICATION, data.getStatus());
        if (userData != null) {
            userData.setCetification(data.getStatus());
            userViewModel.update(userData);
        }
        cetification = data.getStatus();
        adapter.notifyDataSetChanged();
    }

    private void closeMarket() {
        if (marketWebSocket != null) {
            marketWebSocket.closeWebSocket();
            marketWebSocket = null;
        }
    }

    public void sendNotification(NoticeListBean noticeListBean) {
        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 5, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        @SuppressLint("WrongConstant") Notification.Builder builder = new Notification.Builder(App.INSTANCE)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setSmallIcon(R.mipmap.app_logo)
                .setTicker("你好呀，小强")
                .setContentTitle(noticeListBean.getReward_type())
                .setContentText(noticeListBean.getReward_content())
                .setContentIntent(resultPendingIntent)
                .setPriority(Notification.VISIBILITY_PUBLIC)
                .setOngoing(false)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(false);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        if (mNotificationManager != null) {
            mNotificationManager.notify(1, notification);
        }
    }
}
